/*使用
*引入 在main.js中，配合login引入后，接收login后的用户信息，在new Vue之前运行
*     import axiosConfig from './assets/js/axios-config.js'
*     login('zsj','123456').then(res=>{
*       axiosConfig(res)
* 调用 let params={
    "ApiType": "WarehouseController",
  "Parameters": [],
  "Method": "GetWarehouses",
  "timeout":5000, //可选 {Number}
  "Loading":true,//可选{Boolean}
  "LoadingTxt":"lodaing",//可选{String}在Loading属性为true时可用，用于显示loading时的文字
  "ShowUnSuccess":true,//可选{Boolean}默认为true,不想统一显示时才设为false
  "UnSuccess":(message)=>{ this.$ref.input.select()} //可选,处理回复状态Success为false是的处理,

    }
    this.$axios(params).then(res=>{
      console.log("测试请求",res)
      if(res.Success){

      }
    }).catch(err=>{

	});
*/

import axios from "axios";
import Vue from "vue";
import Store from "./../../vuex/index";
import store2 from "./../../vuex";
/**
 *
 * @param {*} userData
 *
 */
export default function(userData) {
  //console.log("登录成功的信息");
  console.log(userData);
  //console.log("store", Store);
  let _this = this;
  axios.defaults.timeout = 30000;
  axios.interceptors.request.use(config => {
    config.url = userData.url;
    // alert(config.url)
    config.data.Context.Ticket = Store.state.userInfo.userData.ticket;
    config.data.Context.InvOrgId = Store.state.userInfo.userData.orgId;
    //console.log("请求拦截器", config);
    return config;
  });
  axios.interceptors.response.use(
    response => {
      // console.log('回复拦截器',response)
      // console.log("刷新ticket成功2");
      if (window.cordova) {
        if (response.data.Success) {
          //请求成功时修改平台的ticket
          Vue.prototype.$hybridApi.refreshUserInfo({
            key: "Ticket",
            value: response.data.Context.Ticket,
            success: obj => {
              console.log("平台ticket修改成功");
            }
          });
        }
      }
      try {
        //刷新ticket缓存
        if (response.data.Context.Ticket) {
          let asyncResult = {
            // url: "/api/invoke",
            url:userData.url,
            userName:Store.state.userInfo.userData.userName,
            userCode:Store.state.userInfo.userData.userCode,
            userId:Store.state.userInfo.userData.userId,
            orgId: Store.state.userInfo.userData.orgId,
            ticket: response.data.Context.Ticket
          };
          console.log("更新的缓存");
          console.log(asyncResult);
          // asyncResult.ticket = response.data.Context.Ticket;
          store2.dispatch("changeUserInfo", {
            attr: "userData",
            val: asyncResult
          });
        }
      } catch (error) {}

      return response;
    },
    err => {
      console.log("报错拦截器", err);
      return Promise.reject(err);
    }
  );
  var loadingMethodList = [];

  function removeLoadingMethodList(method) {
    var index = loadingMethodList.indexOf(method);
    if (index > -1) {
      loadingMethodList.splice(index, 1);
    }
    let len = loadingMethodList.length;
    if (len == 0) {
      Vue.$vux.loading.hide();
    }
  }
  //  接口调用
  Vue.prototype.$axios = function(params) {
    if (params.Loading) {
      // alert( userData.url)
      //如果请求需要loading提示
      var index = loadingMethodList.indexOf(params.Method);
      if (!Vue.$vux.loading.isVisible() && index == -1) {
        Vue.$vux.loading.show({
          text: params.LoadingTxt ? params.LoadingTxt : ""
        });
        loadingMethodList.push(params.Method);
      }
    }
    let promise = new Promise(function(resolve, reject) {
      // alert(userData.url)
      Vue.axios
        .post(
          userData.url,
          {
            ApiType: params.ApiType,
            Parameters: params.Parameters,
            Method: params.Method,
            // Context: {
            //   Ticket: Store.state.userInfo.userData.ticket,
            //   InvOrgId: Store.state.userInfo.userData.orgId
            // }
            Context: {
              Ticket: userData.ticket,
              InvOrgId: userData.orgId
            }
          },
          {
            timeout: params.timeout || 10000
          }
        )
        .then(res => {
          console.log("parmas", params, "ticket1", userData.ticket);
          let data = JSON.parse(res.config.data);
          removeLoadingMethodList(data.Method); //移除并判断隐藏loading提示
          if (!res.data.Success && !(params.ShowUnSuccess === false)) {
            //统一配置请求不成功时的提示
            Vue.$vux.alert.show({
              // text: err.toString(),
              title: "提示",
              content: res.data.Message,
              // width: '5rem',
              // time: 2000,
              // position: 'middle',
              // type: "text",
              onHide() {
                params.UnSuccess && params.UnSuccess(res.data.Message);
              }
            });
          } else if (!res.data.Success) {
            params.UnSuccess && params.UnSuccess(res.data.Message);
          }
          resolve(res.data);
        })
        .catch(err => {
          let errObj = JSON.parse(JSON.stringify(err)).response;
          // alert(errObj.config.data)
          if (errObj) {
            let currenMethod = JSON.parse(errObj.config.data).Method;
            removeLoadingMethodList(currenMethod); //移除并判断隐藏loading提示
            let status = JSON.parse(JSON.stringify(err)).response.status;
            console.log("err", err, "status", status, "errObj", errObj);
           
            switch (status) {
              case 400: //提交数据的字段名称或者是字段类型和后台的实体类不一致，导致无法封装；
                Vue.$vux.toast.show({
                  // text: err.toString(),
                  text: "400请求无效 (Bad request)",
                  width: "5rem",
                  time: 2000,
                  position: "middle",
                  type: "text"
                });
                break;
              case 401: //Ticket失效
                Vue.$vux.toast.show({
                  // text: err.toString(),
                  text: errObj.data.Message,
                  width: "5rem",
                  time: 2000,
                  position: "middle",
                  type: "text"
                });
                break;
              case 404: //
                break;
              case 500:
                Vue.$vux.toast.show({
                  text: err + ",连接网络失败",
                  width: "5rem",
                  time: 2000,
                  position: "middle",
                  type: "text"
                });
                break;
              default:
                Vue.$vux.toast.show({
                  text: errObj.data.Message,
                  width: "5rem",
                  time: 2000,
                  position: "middle",
                  type: "text"
                });
            }
          } else {

            alert(JSON.stringify(err))

            
            if (Vue.$vux.loading.isVisible()) {
              Vue.$vux.loading.hide();
            } //如果当前有显示loading就先隐藏
            Vue.$vux.toast.show({
              text: JSON.stringify(err) + "连接服务器失败",
              width: "5rem",
              time: 2000,
              position: "middle",
              type: "text"
            });
          }
          reject(err);
        });
    });
    return promise;
  };
}
